package bzapps.weynak.fb;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;
import bzapps.weynak.Settings;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;

public class FbSync {

	public String IP = "http://www.bz-apps.com/weynak";

	public String URL_LOGIN = "/authent.php?log_in=logmein";

	public String URL_FRIENDS = "/friends.php?manage_friends=update_friends";

	public String id;
	static final String APP_ID = "119791898115838";

	AsyncFacebookRunner mAsyncRunner;

	Facebook mFacebook;

	public FbSync(Context context) {
		mFacebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(mFacebook);
	    SessionStore.restore(mFacebook, context);
		if (mFacebook.isSessionValid()) {
		  
		mAsyncRunner.request(
				"me/&fields=id,first_name,last_name,gender,birthday,picture",
				new IdRequestListener());
		}
	}

	public class IdRequestListener extends BaseRequestListener {

		@Override	
		public void onComplete(String response, Object state) {

			Log.d("WEYNAK.Friends Request", "response.length(): "
					+ response.length());

			Log.d("WEYNAK.Friends Request", "Response: " + response);

			ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();

			nvp.add(new BasicNameValuePair("credentials", response));

			try {

				HttpClient httpclient = new DefaultHttpClient();

				HttpConnectionParams.setConnectionTimeout(httpclient
						.getParams(), 10000);

				HttpPost httppost = new HttpPost(IP + URL_LOGIN);

				httppost.setEntity(new UrlEncodedFormEntity(nvp));

				HttpResponse resp = httpclient.execute(httppost);

				id = EntityUtils.toString(resp.getEntity());

				if (resp.getStatusLine().getStatusCode() == 200)

				{

					mAsyncRunner.request("me/friends&fields=id",
							new FriendsRequestListener());

				}

				Log.d("WEYNAK.return_statement", id);

				Log.d("WEYNAK.query", response);

				Log.d("WEYNAK.authent_state", String.valueOf(resp
						.getStatusLine().getStatusCode()));

			} catch (Exception e) {

				Log.e("WEYNAK", "Error in http connection " + e.toString());

			}

		}

		@Override
		public void onFacebookError(FacebookError e) {

		}

	}

	public class FriendsRequestListener extends BaseRequestListener {

		@Override
		public void onComplete(String response, Object state) {

			try {

				Log.d("WEYNAK.Friends Request", "response.length(): "
						+ response.length());

				Log.d("WEYNAK.Friends Request", "Response: " + response);

				final JSONObject json = new JSONObject(response);

				JSONArray d = json.getJSONArray("data");

				String friends = d.toString();

				ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();

				nvp.add(new BasicNameValuePair("friends", friends));

				nvp.add(new BasicNameValuePair("uid", id));

				Log.d("WEYNAK.friends", friends);

				try {

					HttpClient httpclient = new DefaultHttpClient();

					HttpConnectionParams.setConnectionTimeout(httpclient
							.getParams(), 10000);

					HttpPost httppost = new HttpPost(IP + URL_FRIENDS);

					httppost.setEntity(new UrlEncodedFormEntity(nvp));

					HttpResponse resp = httpclient.execute(httppost);

					if (resp.getStatusLine().getStatusCode() == 200)

					{
						Settings.handler.sendEmptyMessage(0);
						Log.v("WEYNAK.Facebook.synchronizing", "done");

					}

					Log.d("WEYNAK.query", friends);

					Log.d("WEYNAK.authent_state", String.valueOf(resp
							.getStatusLine().getStatusCode()));

				} catch (Exception e) {

					Log.e("WEYNAK", "Error in http connection " + e.toString());

				}

			} catch (JSONException e) {

				Log.w("WEYNAK.Facebook", "JSON Error in response");

			}

		}

		@Override
		public void onFacebookError(FacebookError e) {

		}

	}

}
